package com.vcsoft.emailresponder.parser;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.vcsoft.emailresponder.config.bean.SMTP;
import com.vcsoft.emailresponder.util.Utility;

public class SMTPParser extends AbstractParser<SMTP>{

	/**
	 * Object of database to set all the properties after parsing done from config.xml
	 */
	SMTP smtpConfig;
	
	/**
	 * Public constructor
	 */
	public SMTPParser() {
	}

	@Override
	public List<SMTP> parse(NodeList nodeList) {
		if(nodeList == null){
			System.out.println("nodeList is null");
			return null;
		}
		
		List<SMTP> smtpConfig = new ArrayList<SMTP>();

		for (int idx = 0; idx < nodeList.getLength(); idx++) {
			SMTP smtp = new SMTP();

			Element element = (Element) nodeList.item(idx);
			//String id = element.getAttribute("ID");

			//Server
			NodeList serverNodes = element.getElementsByTagName("server");
			Element eleServer = (Element) serverNodes.item(0);
			smtp.setServer(Utility.getCharacterDataFromElement(eleServer));
			
			// User Name
			NodeList userNameNodes = element.getElementsByTagName("userName");
			Element eleUserName = (Element) userNameNodes.item(0);
			smtp.setUserName(Utility.getCharacterDataFromElement(eleUserName));
			
			// password
			NodeList pwdNameNodes = element.getElementsByTagName("password");
			Element elePassword = (Element) pwdNameNodes.item(0);
			smtp.setPassword(Utility.getCharacterDataFromElement(elePassword));
			
			// port
			NodeList portNodes = element.getElementsByTagName("port");
			Element elePort = (Element) portNodes.item(0);
			int port = Integer.parseInt(Utility.getCharacterDataFromElement(elePort));
			smtp.setPort(port);
			
			smtpConfig.add(smtp);
		}
		return smtpConfig;
	}

	private void printParsedData(){
		NodeList nodes = super.getNodeList("smtp");
		SMTPParser spe = new SMTPParser();
		List<SMTP> dbc = spe.parse(nodes);
		for (Iterator<SMTP> iterator = dbc.iterator(); iterator.hasNext();) {
			SMTP database = iterator.next();
			System.out.println(database.getServer());
			System.out.println(database.getUserName());
			System.out.println(database.getPassword());
			System.out.println(database.getPort());
		}
	}
	 
	public static void main(String[] args) {
		SMTPParser spe = new SMTPParser();
		spe.printParsedData();
	}
}
